package com.zjitc.common;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.util.Date;

/**
 * Create by IntelliJ IDEA
 *
 * @author: jsonor
 * @date-Time: 2018/4/12 16:31
 * @description:
 */
public class Gsonal {

  public static <T> String tojson(T object) {
    Gson gson = new Gson();
    return gson.toJson(object);
  }

  public static <T> T fromJson(String json, Class<T> classOfT) {
    GsonBuilder builder = new GsonBuilder();

    // Register an adapter to manage the date types as long values
    builder.registerTypeAdapter(Date.class, new JsonDeserializer<Date>() {
      @Override
      public Date deserialize(JsonElement json, Type typeOfT,
          JsonDeserializationContext context) throws JsonParseException {
        return new Date(json.getAsJsonPrimitive().getAsString());
      }
    });

    return builder.create().fromJson(json, classOfT);

//    Gson gson = new Gson();
//    return gson.fromJson(json,classOfT);
  }
}
